package com.jumper.study.admin.controller;

import org.springframework.web.bind.annotation.RestController;

import com.jumper.study.admin.service.AccountService;
import com.jumper.study.common.api.CommonPageResult;
import com.jumper.study.common.api.CommonResult;
import com.jumper.study.common.api.ResultCode;
import com.jumper.study.db.model.Account;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jumper.study.admin.dto.req.AccountCreateGroup;
import com.jumper.study.admin.dto.req.AccountReq;
import com.jumper.study.admin.dto.resp.AccountResp;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@RestController
@RequestMapping("/api/backend/accounts")
public class AccountController {
    @Value("${study-setting.admin.username}")
    private String ADMIN_NAME;
    
    @Autowired
    private AccountService accountService;

    @GetMapping("")
    public CommonPageResult<List<AccountResp>> getList(@RequestParam(name="page", defaultValue = "1") Long p, @RequestParam(defaultValue = "10") Long pageSize) {
        Page<Account> page = Page.of(p, pageSize);
        accountService.page(page, null);
        List<AccountResp> accountList = page.getRecords().stream()
                    .map(m -> new AccountResp(m.getId(), m.getUsername(), m.getName(), m.getAvatar(), m.getUpdatedAt()))
                    .toList();

        return CommonPageResult.restPage(page.getCurrent(), page.getSize(), page.getTotal(), accountList);
    }

    @PostMapping("/")
    public CommonResult<Boolean> create(@RequestBody @Validated(value={AccountCreateGroup.class}) AccountReq req) {
        Account account = accountService.getByUsername(req.getUsername());
        if (account != null) {
            return CommonResult.validateFailed("用户名已存在");
        }
        account = new Account();
        account.setUsername(req.getUsername());
        account.setName(req.getName());
        account.setPassword(req.getPassword());
        boolean result = accountService.save(account);

        return CommonResult.success(result);
    }

    @PostMapping("/{id}")
    public CommonResult<Boolean> update(@PathVariable int id, @RequestBody @Validated AccountReq req) {
        Account account = accountService.getById(id);
        if (account == null) {
            return CommonResult.failed(ResultCode.NOT_FOUND.getCode(), ResultCode.NOT_FOUND.getMessage());
        }
        account.setName(req.getName());
        account.setPassword(req.getPassword());
        boolean result = accountService.updateById(account);

        return CommonResult.success(result);
    }
    
    @PostMapping("/{id}/reset")
    public CommonResult<Boolean> resetPassword(@PathVariable Long id) {
        Account account = accountService.getById(id);
        if (account == null) {
            return CommonResult.notFound();
        }

        String newPwd = account.getUsername() + "123456";
        boolean result = accountService.resetPasswordById(account.getUsername(), newPwd);
        return CommonResult.success(result);
    }
    

    @DeleteMapping("/{id}")
    public CommonResult<Boolean> delete(@PathVariable int id) {
        Account account = accountService.getById(id);
        if (account == null) {
            return CommonResult.success(true);
        }
        if (ADMIN_NAME.equals(account.getUsername())) {
            return CommonResult.validateFailed("管理员无法删除");
        }
        boolean result = accountService.removeById(account);

        return CommonResult.success(result);
    }

    @GetMapping("/{id}")
    public CommonResult<AccountResp> getItem(@PathVariable int id) {
        Account account = accountService.getById(id);
        if (account == null) {
            return CommonResult.failed(ResultCode.NOT_FOUND.getCode(), ResultCode.NOT_FOUND.getMessage());
        }
        AccountResp resp = new AccountResp();
        resp.setId(account.getId());
        resp.setUsername(account.getUsername());
        resp.setName(account.getName());
        resp.setUpdatedAt(account.getUpdatedAt());

        return CommonResult.success(resp);
    }
}
